<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拼团项目 - 商品详情页</title>
    <link rel="stylesheet" href="css/index.css">

</head>
<body>
<!-- 轮播图 -->
<div class="swiper-container">
    <div class="swiper-wrapper">
        <div class="swiper-slide"><img src="./images/sku-13811216-01.png"></div>
        <div class="swiper-slide"><img src="./images/sku-13811216-02.png"></div>
        <div class="swiper-slide"><img src="./images/sku-13811216-03.png"></div>
    </div>
    <div class="swiper-pagination"></div>
</div>

<div class="container">
    <div class="price-info">
        <div class="price">
            <span class="price-value" id="payPrice"></span>
            <span class="price-label"></span>
        </div>
        <div class="special-tags">
            <!-- 动态填充超值补贴 -->
            <div class="special-tag" id="deductionPrice"></div>
            <div class="sales-info" id="allTeamUserCount"></div>
        </div>
    </div>
</div>

<!-- 商品信息 -->
<div class="product-info">
    <span class="promotion-tag">拼团大促</span>
    <span class="product-title">手写MyBatis：渐进式源码实践（全彩）</span>
    <span class="promotion-text"></span> <!-- 动态填充促销文本 -->
</div>

<!-- 拼单列表容器 -->
<div class="group-list" id="groupList">
    <!-- 大促优惠，只有在teamList有数据时显示 -->

    <!-- 拼团项将在这里动态生成 -->
</div>

<!-- 空白区域 -->
<div class="area"></div>

<!-- 底部操作栏 -->
<div class="action-bar">
    <button class="action-btn buy-alone"></button>
    <button class="action-btn group-buy"></button>
</div>
<script src="js/index.js"></script>
<script>


    // 新增支付确认函数
    function showPaymentConfirm(price) {
        // 创建遮罩层
        const overlay = document.createElement('div');
        overlay.className = 'payment-overlay';

        // 创建弹窗内容
        const modal = document.createElement('div');
        modal.className = 'payment-modal';
        modal.innerHTML = `
        <h3>支付确认</h3>
        <p>商品金额：￥${price}</p>
        <p>买家账号：<span class="copyable" data-copy="raeeey2153@sandbox.com">raeeey2153@sandbox.com</span></p>
        <p>登录密码：111111</p>
        <p>支付密码：111111</p>
        <div class="modal-buttons">
            <button class="confirm-btn">确认支付</button>
            <button class="cancel-btn">取消支付</button>
        </div>
    `;

        // 确认支付处理
        modal.querySelector('.confirm-btn').addEventListener('click', function() {
            const form = document.querySelector('form');
            if (form) form.submit();
            overlay.remove();
        });

        // 取消支付处理
        modal.querySelector('.cancel-btn').addEventListener('click', function() {
            document.querySelectorAll('form').forEach(form => form.remove());
            overlay.remove();
        });

        // 添加复制功能
        modal.querySelector('.copyable').addEventListener('click', function() {
            const textToCopy = this.getAttribute('data-copy');
            navigator.clipboard.writeText(textToCopy).then(() => {
                alert('买家账号已复制到剪贴板');
            }).catch(err => {
                console.error('无法复制文本: ', err);
            });
        });

        overlay.appendChild(modal);
        document.body.appendChild(overlay);
    }

    function obfuscateUserId(userId) {
        if (userId.length <= 4) {
            // 如果 userId 的长度小于或等于 4，则无需替换任何字符
            return userId;
        } else {
            // 获取前两位和后两位
            const start = userId.slice(0, 2);
            const end = userId.slice(-2);
            // 计算中间部分应该被替换成多少个 *
            const middle = '*'.repeat(userId.length - 4);
            // 返回成功替换后的字符串
            return `${start}${middle}${end}`;
        }
    }

    document.addEventListener('DOMContentLoaded', function() {
        // 根据测试诉求，设置基础地址
        var sPayMallUrl = "http://127.0.0.1:8080";
        var groupBuyMarketUrl = "http://127.0.0.1:8091";
        var goodsId = "9890001";

        // 获取信息
        var userId = getCookie("loginToken");
        if (!userId) {
            window.location.href = "login.html"; // 跳转到登录页
            return;
        }

        // 请求接口数据
        fetch(groupBuyMarketUrl + '/api/v1/gbm/index/query_group_buy_market_config', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                userId: userId,
                source: "s01",
                channel: "c01",
                goodsId: goodsId
            })
        })
            .then(response => response.json())
            .then(res => {
                if(res.code !== '0000') return;

                const { activityId, goods, teamList, teamStatistic } = res.data;
                const groupList = document.querySelector('.group-list');
                const promotionText = document.querySelector('.promotion-text');


                const groupBanner = document.getElementById('groupBanner');
                const deductionValue = document.getElementById('deductionValue');
                const allTeamUserCounting = document.getElementById('allTeamUserCounting');

                const payPrice = document.getElementById('payPrice');
                const allTeamUserCount = document.getElementById('allTeamUserCount');


                const deductionPrice = document.getElementById('deductionPrice'); // 获取超值补贴元素


                // 更新促销信息

                payPrice.textContent = `￥${goods.payPrice.toFixed(2)}`;
                deductionPrice.textContent = `超值补贴直降￥${goods.deductionPrice.toFixed(2)}`;


                // 检查 teamStatistic.allTeamUserCount 是否为 null 或无效
                if (teamStatistic.allTeamUserCount === null || isNaN(teamStatistic.allTeamUserCount)) {
                    allTeamUserCount.style.display = 'none'; // 隐藏该元素
                } else {
                    allTeamUserCount.style.display = 'block'; // 显示该元素
                    allTeamUserCount.textContent = `已拼${teamStatistic.allTeamUserCount}件`;
                }

                // 如果teamList有数据，显示大促优惠信息和拼团列表
                if (teamList.length !== 0) {
                    groupList.innerHTML = ""  // 清空拼团列表容器

                    // 生成大促优惠信息
                    const groupBanner = document.createElement('div');
                    groupBanner.classList.add('group-banner');
                    groupBanner.innerHTML = `
        <span>大促优惠 | 已直降 <span id="deductionValue">${goods.deductionPrice.toFixed(2)}</span> 元，<span id="allTeamUserCounting">${teamStatistic.allTeamUserCounting}</span> 人在抢</span>
    `;
                    groupList.appendChild(groupBanner); // 添加到容器中


                    // 生成拼团列表
                    teamList.forEach(team => {
                        const remaining = team.targetCount - team.lockCount;
                        const countdown = team.validTimeCountdown;

                        // 判断当前用户是否是该拼团的发起人
                        if (userId == team.userId) {
                            outTradeNo = team.outTradeNo;
                        }

                        const groupItem = document.createElement('div');
                        groupItem.classList.add('group-item');
                        groupItem.innerHTML = `
                    <div>
                        <div class="user-info" data-teamId="${team.teamId}">${team.userId}</div>
                        <div class="group-status">
                            <span>组队仅剩${remaining}人，拼单即将结束</span>
                            <span class="countdown">${countdown}</span>
                        </div>
                    </div>
                    <div class="right">
                        <button class="group-btn" data-price="${goods.payPrice.toFixed(2)}">参与拼团</button>
                    </div>
                    `;

                        // 将倒计时对象传递给 Countdown 类
                        const countdownElement = groupItem.querySelector('.countdown');
                        new Countdown(countdownElement, countdown, groupItem); // 初始化倒计时并传递 groupItem

                        groupList.appendChild(groupItem); // 使用appendChild填充容器
                    });
                } else {
                    // 如果teamList为空，显示提示信息
                    groupList.innerHTML = `
                         <div class="group-item empty-tips">
                             <div class="tips-content" style="color: red">
                                 小伙伴，赶紧去开团吧，做村里最靓的仔！🎉
                             </div>
                         </div>
                    `;
                }


                // 更新底部按钮
                const buyAloneBtn = document.querySelector('.buy-alone');
                const groupBuyBtn = document.querySelector('.group-buy');
                buyAloneBtn.textContent = `单独购买(￥${goods.originalPrice.toFixed(2)})`;
                buyAloneBtn.dataset.price = goods.originalPrice;
                groupBuyBtn.textContent = `开团购买(￥${goods.payPrice.toFixed(2)})`;
                groupBuyBtn.dataset.price = goods.payPrice;

                // 绑定支付事件[拼团购买]
                document.querySelectorAll('.group-btn, .group-buy').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const button = this;
                        const price = button.dataset.price;

                        // 获取拼团ID
                        let teamId = null;
                        if (this.classList.contains('group-btn')) {
                            const groupItem = this.closest('.group-item');
                            const userInfo = groupItem.querySelector('.user-info');
                            teamId = userInfo.dataset.teamid;
                        }

                        var url = sPayMallUrl + '/api/v1/alipay/create_pay_order';

                        var requestBody = {
                            userId: userId,
                            productId: goods.goodsId,
                            teamId: teamId,
                            activityId: activityId,
                            marketType: 1
                        };

                        fetch(url, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify(requestBody) // 将请求体转换为JSON字符串
                        })
                            .then(response => response.json()) // 解析JSON格式的响应
                            .then(json => {
                                if (json.code === "0000") { // 假设成功的code是"0000"
                                    document.querySelectorAll('form').forEach(form => form.remove());
                                    document.body.insertAdjacentHTML('beforeend', json.data);
                                    // 只有在没有错误时才弹出支付确认
                                    showPaymentConfirm(goods.payPrice); // 确认支付时显示拼团价格
                                } else {
                                    // 如果有错误，弹出错误信息提示框
                                    alert('错误信息: ' + json.info); // 弹出错误信息
                                }
                            })
                            .catch(error => {
                                // 如果请求失败，弹出请求失败的错误提示框
                                alert('请求错误: ' + error.message); // 弹出请求失败的错误信息
                                console.error('Error:', error);
                            });
                    });
                });



                // 绑定支付事件[单独购买]
                document.querySelectorAll('.buy-alone').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const button = this;
                        const price = button.dataset.price;

                        var requestBody = {
                            userId: userId,
                            productId: goods.goodsId,
                            marketType: 0 // 0 表示单独购买，不参与拼团
                        };

                        fetch(sPayMallUrl + '/api/v1/alipay/create_pay_order', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify(requestBody) // 将请求体转换为JSON字符串
                        })
                            .then(response => response.json()) // 解析JSON格式的响应
                            .then(json => {
                                if (json.code === "0000") { // 假设成功的code是"0000"
                                    document.querySelectorAll('form').forEach(form => form.remove());
                                    document.body.insertAdjacentHTML('beforeend', json.data);
                                    // 在支付确认时传递原价
                                    showPaymentConfirm(goods.originalPrice); // 确认支付时显示原价
                                } else {
                                    // 弹出错误提示框
                                    alert('错误信息: ' + json.info); // 弹出错误信息
                                }
                            })
                            .catch(error => {
                                // 如果请求失败，弹出错误提示框
                                alert('请求错误: ' + error.message); // 弹出请求失败的错误信息
                                console.error('Error:', error);
                            });
                    });
                });



                // 启动倒计时
                document.querySelectorAll('.countdown').forEach(el => {
                    new Countdown(el, el.textContent);
                });

            });

    });
</script>

</body>
</html>